package com.geek.factory.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.geek.factory.constant.InvoiceConstants;
import com.geek.factory.dto.InvoiceQueryDTO;
import com.geek.factory.dto.InvoiceRequestDTO;
import com.geek.factory.dto.InvoiceResponseDTO;
import com.geek.factory.service.NuonuoInvoiceService;
import lombok.extern.slf4j.Slf4j;
import nuonuo.open.sdk.NNOpenSDK;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 诺诺网发票服务实现类
 */
@Service
@Slf4j
public class NuonuoInvoiceServiceImpl implements NuonuoInvoiceService {

    @Autowired
    private RestTemplate restTemplate;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public InvoiceResponseDTO applyInvoice(InvoiceRequestDTO requestDTO) {
        try {
            log.info("开始申请开具发票，订单号：{}", requestDTO.getOrderNo());

            // 构建请求参数
            String content = buildInvoiceContent(requestDTO);

            // 生成唯一标识
            String senid = UUID.randomUUID().toString().replace("-", "");

            // 使用NNOpenSDK调用API
            NNOpenSDK sdk = NNOpenSDK.getIntance();
            String token = ""; // 沙箱环境下token可以为空

            String result = sdk.sendPostSyncRequest(
                InvoiceConstants.TEST_URL,
                senid,
                InvoiceConstants.TEST_APP_KEY,
                InvoiceConstants.TEST_APP_SECRET,
                token,
                InvoiceConstants.TEST_SALER_TAX_NUM,
                InvoiceConstants.APPLY_METHOD,
                content
            );

            log.info("诺诺网响应：{}", result);

            // 解析响应
            return parseResponse(result);

        } catch (Exception e) {
            log.error("申请开具发票失败", e);
            InvoiceResponseDTO errorResponse = new InvoiceResponseDTO();
            errorResponse.setCode("ERROR");
            errorResponse.setMessage("申请开具发票失败：" + e.getMessage());
            return errorResponse;
        }
    }

    @Override
    public InvoiceResponseDTO queryInvoice(InvoiceQueryDTO queryDTO) {
        try {
            log.info("开始查询发票，订单号：{}", queryDTO.getOrderNo());

            // 构建请求参数
            String content = buildQueryContent(queryDTO);

            // 生成唯一标识
            String senid = UUID.randomUUID().toString().replace("-", "");

            // 使用NNOpenSDK调用API
            NNOpenSDK sdk = NNOpenSDK.getIntance();
            String token = ""; // 沙箱环境下token可以为空

            String result = sdk.sendPostSyncRequest(
                InvoiceConstants.TEST_URL,
                senid,
                InvoiceConstants.TEST_APP_KEY,
                InvoiceConstants.TEST_APP_SECRET,
                token,
                InvoiceConstants.TAX_NUM,
                InvoiceConstants.APPLY_METHOD1,
                content
            );

            log.info("诺诺网查询响应：{}", result);

            // 解析响应
            return parseResponse(result);

        } catch (Exception e) {
            log.error("查询发票失败", e);
            InvoiceResponseDTO errorResponse = new InvoiceResponseDTO();
            errorResponse.setCode("ERROR");
            errorResponse.setMessage("查询发票失败：" + e.getMessage());
            return errorResponse;
        }
    }

    /**
     * 构建发票申请内容
     */
    private String buildInvoiceContent(InvoiceRequestDTO requestDTO) {
        StringBuilder content = new StringBuilder();
        content.append("{\"order\":{");
        
        // 发票明细
        content.append("\"invoiceDetail\":[");
        for (InvoiceRequestDTO.InvoiceDetailDTO detail : requestDTO.getInvoiceDetail()) {
            content.append("{");
            content.append("\"taxRate\":\"").append(detail.getTaxRate()).append("\",");
            content.append("\"invoiceLineProperty\":\"").append(detail.getInvoiceLineProperty()).append("\",");
            content.append("\"selfCode\":\"").append(detail.getSelfCode()).append("\",");
            content.append("\"listName\":\"").append(detail.getListName()).append("\",");
            content.append("\"specType\":\"").append(detail.getSpecType()).append("\",");
            content.append("\"goodsName\":\"").append(detail.getGoodsName()).append("\",");
            content.append("\"goodsCode\":\"").append(detail.getGoodsCode()).append("\",");
            content.append("\"taxExcludedAmount\":\"").append(detail.getTaxExcludedAmount()).append("\",");
            content.append("\"withTaxFlag\":\"").append(detail.getWithTaxFlag()).append("\",");
            content.append("\"num\":\"").append(detail.getNum()).append("\",");
            content.append("\"tax\":\"").append(detail.getTax()).append("\",");
            content.append("\"unit\":\"").append(detail.getUnit()).append("\",");
            content.append("\"deduction\":\"").append(detail.getDeduction()).append("\",");
            content.append("\"price\":\"").append(detail.getPrice()).append("\"");
            content.append("}");
        }
        content.append("],");
        
        // 购方信息
        content.append("\"buyerName\":\"").append(requestDTO.getBuyerName()).append("\",");
        content.append("\"buyerAddress\":\"").append(requestDTO.getBuyerAddress()).append("\",");
        content.append("\"buyerTaxNum\":\"").append(requestDTO.getBuyerTaxNum()).append("\",");
        content.append("\"buyerPhone\":\"").append(requestDTO.getBuyerPhone()).append("\",");
        content.append("\"email\":\"").append(requestDTO.getEmail()).append("\",");
        
        // 发票类型和配置
        content.append("\"invoiceType\":\"").append(InvoiceConstants.INVOICE_TYPE).append("\",");
        content.append("\"invoiceLine\":\"").append(InvoiceConstants.INVOICE_LINE).append("\",");
        content.append("\"listFlag\":\"").append(InvoiceConstants.LIST_FLAG).append("\",");
        content.append("\"pushMode\":\"").append(InvoiceConstants.PUSH_MODE).append("\",");
        
        // 销方信息
        content.append("\"salerAccount\":\"").append(InvoiceConstants.TEST_SALER_ACCOUNT).append("\",");
        content.append("\"salerAddress\":\"").append(InvoiceConstants.TEST_SALER_ADDRESS).append("\",");
        content.append("\"salerTelr\":\"").append(InvoiceConstants.TEST_SALER_TEL).append("\",");
        content.append("\"salerTaxNum\":\"").append(InvoiceConstants.TEST_SALER_TAX_NUM).append("\",");
        
        // 订单信息
        content.append("\"orderNo\":\"").append(requestDTO.getOrderNo()).append("\",");
        content.append("\"invoiceDate\":\"").append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))).append("\",");
        
        // 开票员信息
        content.append("\"clerk\":\"张三\",");
        content.append("\"checker\":\"张三\",");
        content.append("\"payee\":\"张三\",");
        content.append("\"payer\":\"张三\",");
        content.append("\"clerkId\":\"1\",");
        content.append("\"extensionNumber\":\"0\"");
        
        content.append("}}");
        
        return content.toString();
    }

    private String buildQueryContent(InvoiceQueryDTO queryDTO) {
    StringBuilder content = new StringBuilder();
    content.append("{");
    content.append("\"isOfferInvoiceDetail\":\"1\",");
    content.append("\"orderNos\":\"").append(queryDTO.getOrderNo()).append("\"");
    if (queryDTO.getInvoiceCode() != null && !queryDTO.getInvoiceCode().isEmpty() &&
        queryDTO.getInvoiceNumber() != null && !queryDTO.getInvoiceNumber().isEmpty()) {
        content.append(",\"serialNos\":\"")
               .append(queryDTO.getInvoiceCode())
               .append(queryDTO.getInvoiceNumber())
               .append("\"");
    }
    content.append("}");
    return content.toString();
}

    /**
     * 解析响应
     */
    private InvoiceResponseDTO parseResponse(String responseBody) {
        try {
            JsonNode rootNode = objectMapper.readTree(responseBody);

            InvoiceResponseDTO response = new InvoiceResponseDTO();
            response.setCode(rootNode.path("code").asText());
            // 诺诺网返回的消息字段有时叫 describe
            response.setMessage(rootNode.path("message").asText().isEmpty() ? rootNode.path("describe").asText() : rootNode.path("message").asText());

            // 兼容诺诺网返回的 result 数组
            if (rootNode.has("result") && rootNode.get("result").isArray() && rootNode.get("result").size() > 0) {
                JsonNode dataNode = rootNode.get("result").get(0);
                InvoiceResponseDTO.InvoiceDataDTO data = new InvoiceResponseDTO.InvoiceDataDTO();

                data.setInvoiceCode(dataNode.path("invoiceCode").asText());
                data.setInvoiceNumber(dataNode.path("invoiceNo").asText());
                data.setCheckCode(dataNode.path("checkCode").asText()); // 新增
                data.setMachineCode(dataNode.path("machineCode").asText());
                // 时间戳转日期字符串
                long invoiceDate = dataNode.path("invoiceDate").asLong(0);
                if (invoiceDate > 0) {
                    data.setInvoiceDate(new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date(invoiceDate)));
                } else {
                    data.setInvoiceDate("");
                }
                data.setStatus(dataNode.path("statusMsg").asText());
                data.setImgUrls(dataNode.path("imgUrls").asText());
                data.setTotalAmount(dataNode.path("orderAmount").asText());
                data.setTaxAmount(dataNode.path("taxAmount").asText());
                data.setBuyerName(dataNode.path("buyerName").asText()); // 新增
                data.setBuyerTaxNum(dataNode.path("buyerTaxNum").asText());

                // 明细
                if (dataNode.has("invoiceItems") && dataNode.get("invoiceItems").isArray()) {
                    List<InvoiceResponseDTO.InvoiceDetailDTO> detailList = new java.util.ArrayList<>();
                    for (JsonNode item : dataNode.get("invoiceItems")) {
                        InvoiceResponseDTO.InvoiceDetailDTO detail = new InvoiceResponseDTO.InvoiceDetailDTO();
                        detail.setGoodsName(item.path("itemName").asText());
                        detail.setSpecType(item.path("itemSpec").asText());
                        detail.setUnit(item.path("itemUnit").asText());
                        detail.setNum(item.path("itemNum").asText());
                        detail.setPrice(item.path("itemPrice").asText());
                        detail.setAmount(item.path("itemAmount").asText());
                        detail.setTaxRate(item.path("itemTaxRate").asText());
                        detail.setTax(item.path("itemTaxAmount").asText());
                        detailList.add(detail);
                    }
                    data.setInvoiceDetail(detailList);
                }

                response.setData(data);
            }

            return response;
        } catch (Exception e) {
            log.error("解析响应失败", e);
            InvoiceResponseDTO errorResponse = new InvoiceResponseDTO();
            errorResponse.setCode("PARSE_ERROR");
            errorResponse.setMessage("解析响应失败：" + e.getMessage());
            return errorResponse;
        }
    }
} 